import { message } from "antd";
import { EventSourcePolyfill } from "event-source-polyfill";

export function sse(url: string, callback: (data: any) => void) {
  if (window.EventSource) {
    const eventSource = new EventSourcePolyfill(url, {
      withCredentials: true,
      headers: {
        Authorization: localStorage.getItem("token") || "",
      },
    });
    eventSource.onopen = (event: any) => {
      console.log("建立连接:", event.status);
    };
    eventSource.onmessage = (event: any) => {
      console.log("收到消息:", event.data);
      callback(event.data);
      if (event.data === 600) {
        message.error("糟糕！签到结束了");
        eventSource.close();
      }
    };
    eventSource.onerror = (event: any) => {
      console.log("连接错误:", event);
      eventSource.close();
    };
    return () => {
      eventSource.close();
    };
  } else {
    message.error("浏览器不支持SSE");
  }
}
